<?php
require_once 'environment.php';

CleanVars($_POST);

$userLogin = $_POST['credentials_username'];
$userPassword = $_POST['credentials_password'];
$rmb = $_POST['_login_remember_me']; 

$remember = ($rmb ? 'true' : 'false');

if(empty($userLogin) && empty($userPassword)) {
    ErrorLogin($userLogin, 'login-username', $remember, '%login_error_1%');
}
else if(empty($userLogin)) {
    ErrorLogin($userLogin, 'login-username', $remember, '%login_error_3%');
}
else if(empty($userPassword)) { 
    ErrorLogin($userLogin, 'login-password', $remember, '%login_error_2%');
}

if(isset($_SESSION['login']['error_captcha'])) {
    if($_SESSION['login']['error_captcha'] >= 4) {
        
        $captcha_response_field = $_POST['recaptcha_response_field'];
        $captcha_challenge_field = $_POST['recaptcha_challenge_field'];
        
        $captcha_result = is_captcha($captcha_challenge_field, $captcha_response_field);
        
        if(!$captcha_result) {
            ErrorLogin($userLogin, 'recaptcha_response_field', $remember, '%login_error_5%');
        }
    }
}

if(!$users->CheckLogin($userLogin, $userPassword)) {
    $_SESSION['login']['error_captcha']++;
    
    if($_SESSION['login']['error_captcha'] >= 4)
        $e = '%login_error_5%';
    else
        $e = '%login_error_4%';
    
    ErrorLogin($userLogin, 'login-password', $remember, $e);
}
else {
    
    $_SESSION['habbo']['email'] = $userLogin;
    $_SESSION['habbo']['password'] = $userPassword;
    $_SESSION['habbo']['connection_type'] = 'habboID';
    
    Location('me');
}

function ErrorLogin($u, $f, $r, $msg) {
    $_SESSION['login']['error_message'] = $msg;
    Location('?username=' . $u . '&rememberme=' . $r . '&focus=' . $f);
}
?>